<?php


/**
 * Notes:
 * PROJECT_NAME : ERP v1.8 重构erp
 * User: 夏鱼儿<397072174@qq.com>
 * Date: 2024/4/12
 * Time: 15:45
 */

namespace app\company\controller;

use app\admin\model\Company;
use app\company\model\Store;
use think\Response;


class Stat extends Base
{

    public function list(): Response
    {
        $gs = Company::find(getCompanyId());
        //基础信息
        $base['goods_rules']      = $gs->companyGoodsRules()->status()->count();//sku 数量
        $base['goods_stock']      = $gs->companyOrderStorages()->sum('quantity');//商品库存数量
        $base['wh_count']         = $gs->warehouses()->count();//仓库数量
        $base['wh_area_count']    = $gs->warehouseAreaSM()->count();//库区数量
        $base['wh_storage_count'] = $gs->WarehouseStorageSM()->count(); //库位数量
        $base['store_count']      = Store::gs()->count(); //门店数量
        $base['car_count']        = $gs->deliverCars()->count();//车辆数量
        $base['line_count']       = $gs->deliverLines()->count();//路线数量

        $map   = [['order_status', 'in', [2, 3, 4]]];
        //运营数据
        $run['m_in_amount']  = $gs->companyOrderDetailSM()->whereMonth('company_order_detail.create_time')->sum('amount');//本月入库金额
        $run['m_out_amount'] = $gs->storeOrderDetailSM($map)->whereMonth('store_order_detail.create_time')->sum('amount');//本月出库金额
        $run['in_amount']    = $gs->companyOrderDetailSM()->sum('amount');//总入库金额
        $run['out_amount']   = $gs->storeOrderDetailSM($map)->sum('amount');//总出库金额
        $run['in_count']     = $gs->companyOrderDetailSM()->sum('quantity');//总入库数量
        $run['out_count']    = $gs->storeOrderDetailSM($map)->sum('quantity');//总出库数量
        $stock               = $gs->companyOrderStorages()->field('id,company_order_detail_id,quantity')->where('quantity', ">", 0)->select()->each(function ($item) {
            $purchasing_price = $item->companyOrderDetail()->value('purchasing_price');//进价
            $item->amount     = $purchasing_price * $item->quantity;
        });
        $run['stock_amount'] = array_sum(array_column($stock->toArray(), 'amount'));//库存金额

        //单据数据
        $order['cg_count']    = $gs->companyOrders()->where('order_status', '<>', 5)->type()->count();//采购单未完成总数
        $order['cg_un_count'] = $gs->companyOrders()->where('order_status', 5)->type()->count();//采购单已完成总数
        $order['xs_count']    = $gs->storeOrders()->whereIn('order_status', [4])->count();//销售已完成总数
        $order['xs_un_count'] = $gs->storeOrders()->whereIn('order_status', [1, 2, 3])->count();//销售单未完成总数

        //商品数据
        $goods['count']     = $gs->storeOrders()->whereIn('order_status', [2, 3, 4])->count();//商品订单总数
        $goods['xs_count']  = $gs->companyOrderStorages()->sum('quantity');//库存
        $goods['xs_amount'] = $gs->storeOrderDetailSM($map)->sum('money');//销售商品总金额

        //预警数据
        return $this->success('请求成功', compact('base', 'run', 'order', 'goods'));
    }
}